package com.ruoyi.xzs.service.impl;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.xzs.domain.Paper;
import com.ruoyi.xzs.domain.Subject;
import com.ruoyi.xzs.enums.PaperEnum;
import com.ruoyi.xzs.mapper.PaperMapper;
import com.ruoyi.xzs.mapper.PaperQuestionMapper;
import com.ruoyi.xzs.mapper.QuestionMapper;
import com.ruoyi.xzs.mapper.SubjectMapper;
import com.ruoyi.xzs.service.IPaperService;
import com.ruoyi.xzs.vo.PaperVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 卷库管理Service业务层处理
 * 
 * @author li
 * @date 2023-03-08
 */
@Service
public class PaperServiceImpl implements IPaperService 
{
    @Autowired
    private PaperMapper paperMapper;

    @Autowired
    private SubjectMapper subjectMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private PaperQuestionMapper paperQuestionMapper;

    /**
     * 查询卷库管理
     * 
     * @param id 卷库管理主键
     * @return 卷库管理
     */
    @Override
    public Paper selectPaperById(Long id)
    {
        return paperMapper.selectPaperById(id);
    }

    /**
     * 查询卷库管理列表
     * 
     * @param papervo 卷库管理
     * @return 卷库管理
     */
    @Override
    public List<PaperVO> selectPaperList(PaperVO papervo)
    {
        // 查询试卷对象
        Paper paper = new Paper();
        BeanUtils.copyProperties(papervo,paper);

        String grade = papervo.getGrade();
        String subjectSelect = papervo.getSubject();
        if (StringUtils.isNotEmpty(grade) || StringUtils.isNotEmpty(subjectSelect)){
            // 查询班级/学科信息
            Subject subject = new Subject();
            subject.setGrade(grade);
            subject.setSubject(subjectSelect);
            Subject subjectOne = subjectMapper.selectOne(subject);
            paper.setSubjectId(subjectOne.getId());
        }

        // 查询指定班级/学科试卷
        List<Paper> papers = paperMapper.selectPaperList(paper);

        List<PaperVO> list = papers.stream().map(item -> {

            // 返回的vo对象
            PaperVO paperReturnVo = new PaperVO();
            BeanUtils.copyProperties(item, paperReturnVo);
            // 查询班级信息
            Subject subjectReturn = subjectMapper.selectSubjectById(item.getSubjectId());
            paperReturnVo.setGrade(subjectReturn.getGrade());
            paperReturnVo.setSubject(subjectReturn.getSubject()+"("+subjectReturn.getGrade()+")");
            // 添加试卷类型编号对应的类型
            for (PaperEnum value : PaperEnum.values()) {
                if (value.getCode().longValue() == item.getType()) {
                    paperReturnVo.setTypeName(value.getMsg());
                }
            }

            return paperReturnVo;

        }).collect(Collectors.toList());

        return list;
    }

    /**
     * 新增卷库管理
     *
     * @param paperVO 卷库管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertPaper(PaperVO paperVO)
    {
        if (paperVO == null){
            throw new ServiceException("无效试卷!!!");
        }

        if (StringUtils.isNull(paperVO.getName()) || StringUtils.isEmpty(paperVO.getName())){
            throw new ServiceException("试卷名称不能为空！！！");
        }

        // 试卷类型
        Long type = paperVO.getType();
        if (null == type || type==0){
            throw new ServiceException("请选择试卷类型");
        }else {
            // 时段试卷  必须设置开始结束时间
            if (type == Long.valueOf(PaperEnum.PAPER_TIME.getCode())) {

                Date limitEndTime = paperVO.getLimitEndTime();
                Date limitStartTime = paperVO.getLimitStartTime();

                if (null == limitEndTime || null == limitStartTime){
                    throw new ServiceException("时段试卷必须设置考试时间！！！");
                }
            }
        }

        // 获取当前用户
        String username = SecurityUtils.getUsername();

        // 查询年级编号
        String subject = paperVO.getSubject();
        String grade = paperVO.getGrade();
        if (StringUtils.isEmpty(subject) || StringUtils.isEmpty(grade)){
            throw new ServiceException("请选择试卷所属班级！！！");
        }
        Subject sg = new Subject();
        sg.setSubject(subject);
        sg.setGrade(grade);
        Subject subjectOne = subjectMapper.selectOne(sg);

        //  计算试卷总分
        // 题目id集合
        String questionIds = paperVO.getQuestionIds();
        String[] questionIdsArr = questionIds.split(",");
        List<String> qIdsStrList = Arrays.asList(questionIdsArr);
        List<Long> qIdsList = qIdsStrList.stream().map(Long::valueOf).collect(Collectors.toList());
        int score = 0;
        if (qIdsList.size() > 0){
            score = questionMapper.appendScore(qIdsList);
        }

        // 试卷新增
        Paper paper = new Paper();
        BeanUtils.copyProperties(paperVO,paper);
        paper.setCreateTime(DateUtils.getNowDate());
        paper.setCreateUser(username);
        paper.setSubjectId(subjectOne.getId());
        paper.setScore(score);
        int i = paperMapper.insertPaper(paper);

        // 试卷题目关联表新增--批量插入
        Long pId = paper.getId();
        paperQuestionMapper.insertPaperQuestions(pId, qIdsList);

        return i;
    }

    /**
     * 修改卷库管理
     * 
     * @param paper 卷库管理
     * @return 结果
     */
    @Override
    public int updatePaper(Paper paper)
    {
        return paperMapper.updatePaper(paper);
    }

    /**
     * 批量删除卷库管理
     * 
     * @param ids 需要删除的卷库管理主键
     * @return 结果
     */
    @Override
    public int deletePaperByIds(Long[] ids)
    {
        return paperMapper.deletePaperByIds(ids);
    }

    /**
     * 删除卷库管理信息
     * 
     * @param id 卷库管理主键
     * @return 结果
     */
    @Override
    public int deletePaperById(Long id)
    {
        return paperMapper.deletePaperById(id);
    }
}
